const userService = require("../services/UserService");
const Result = require("../utils/result");
const UserJoi = require("../modules/validator/UserJoi");
const bcrypt = require("bcrypt");
//各种js数据校验
const Joi = require("joi");
const result = new Result();
const saltRounds = 10;
module.exports = {
  //登录
  async login(ctx) {
    let user = ctx.request.body;
    let res = await userService.login(user);
    const resBranch = {
      suc: () => result.success("登录成功", res.data),
      fail: () => result.error(res.msg),
    };
    ctx.body = res.code ? resBranch.suc() : resBranch.fail();
  },

  async register(ctx) {
    const user = ctx.request.body;
    const { error } = UserJoi.validate(user, {
      bortEarly: false,
      allowUnknown: true,
    });
    if (error) {
      ctx.body = result.error("数据验证不通过,请提供正确的数据格式", error);
    }
    // 注册的时候给一个默认头像,在个人资料页,用户可以更改头像
    // user.avatar = 'defaultAvatar.png'

    //加密密码
    try {
      user.password = await bcrypt.hash(user.password, saltRounds);
    } catch (error) {
      ctx.body = result.error("密码加密时执行出错!", error);
      return;
    }
    const { data, code, msg } = await userService.register(user);
    ctx.body = code ? result.success("注册成功", data) : result.error(msg);
    console.log(user, "-----user------", ctx);
  },
  getDetail() {},
};
